package epam.marchenko.library.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import epam.marchenko.library.domain.User;

@Repository(value="userRepository")
public class UserRepositoryJpaImpl implements UserRepository {

	@PersistenceContext
	private EntityManager em;

	public UserRepositoryJpaImpl() {}
	
	public UserRepositoryJpaImpl(EntityManager em) {
		this.em = em;
	}
	
	public User findByLogin(String login) {
		TypedQuery<User> query = em.createNamedQuery("User.findByLogin",
				User.class);
		query.setParameter("login", login);
		return query.getSingleResult(); 
	}

	
	public User findById(int id) {
		return em.find(User.class, id);
	}

	public User find(User user) {
		return em.find(User.class, user.getId());
	}
	
	public List<User> findAll() {
		TypedQuery<User> query = em.createNamedQuery("User.findAll",
				User.class);
		return query.getResultList();
	}

	@Transactional
	public void create(User user) {
		em.persist(user);
	}

	@Transactional
	public void deleteById(int id) {
		em.remove(findById(id));
	}

	@Transactional
	public void delete(User user) {
		em.remove(findById(user.getId()));
	}

	@Transactional
	public void update(User user) {
		em.merge(user);
	}

	@Override
	public List<User> searchByName(String searchedName) {
		TypedQuery<User> query = em.createNamedQuery("User.searchByName",
				User.class);
		query.setParameter("name", "%"+searchedName+"%");
		return query.getResultList();
	}

	@Override
	public List<User> findPart(int pageNum, int perPage) {
		TypedQuery<User> query = em.createNamedQuery("User.findAll", User.class);
		query.setFirstResult((pageNum-1) * perPage); 
		query.setMaxResults(perPage);
		return query.getResultList();
	}

	@Override
	public Long countUsers() {
		TypedQuery<Long> query = em.createNamedQuery("User.countUsers",
				Long.class);
		return query.getSingleResult(); 
	}
}
